package com.itheima.web; /**
 * @author tongchen
 * @create 2022-11-29 15:29
 */

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.utils.SessionnFactroyUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收值
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        SqlSessionFactory sqlSessionFactory = SessionnFactroyUtils.getFactory();
        //2.2创建sqlsession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //2.3获取mapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //执行方法
        User user = mapper.selectByName(username);
        if(user==null){
            //创建对象并添加
            User user1 = new User();
            user1.setUsername(username);
            user1.setPassword(password);
            mapper.addUser(user1);
            //提交事务
            sqlSession.commit();
            //释放资源
            sqlSession.close();
        }
        else{
            //给出提示信息
            //1.修改字符集
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write("注册失败");
        }
        //释放资源
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
